package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    /**
     * 菜品分类分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")   //1 定义一个接收get请求的方法 接收参数为page pageSize
    public R<Page> page(@RequestParam(required = false, defaultValue = "1") int page,
                        @RequestParam(required = false, defaultValue = "10") int pageSize) {
        //2 构建分页构造器  传入接受的参数page pageSize
        Page<Category> categoryPage = new Page<>(page, pageSize);
        //3 构建条件构造器 按照sort进行正序排序
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        //4 调用service方法进行分页查询
        categoryService.page(categoryPage, wrapper);
        //5 返回结果 categoryPage
        return R.success(categoryPage);
    }

    /**
     * 菜品添加
     * @param category
     * @return
     */
    @PostMapping   //1 定义一个接收get请求的方法 接收参数为category
    public R<String> save(@RequestBody Category category){
        log.info("category{}",category);
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 修改菜品分类
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody  Category category){
        log.info("category{}",category);
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 删除菜品分类
     * @param id
     * @return
     */
    @DeleteMapping  // 1 定义一个接收Delete请求的方法 参数为Long
    public R<String> delete(Long id){
        //2 调用service层方法进行删除
        categoryService.removeById(id);
        return R.success("删除成功");
    }
}
